package com.cmj.aspect;

import com.alibaba.fastjson.JSON;
import com.cmj.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义切片类
 * 1.确定切点
 *  这里是自定义了一个注解
 * 2.设置通知方法
 */

@Component //容器管理
@Aspect //定义为切片类
@Slf4j
public class LogAspect {

    //1.确定切点
    @Pointcut("@annotation(com.cmj.annotation.SystemLog)")
    public void pt(){}

    //2.设置通知方法
    @Around("pt()")
    public void printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        
        Object ret;
        try {
            
            handlerBefore(joinPoint);//前置通知
            ret = joinPoint.proceed();//方法执行
            handlerAfter(ret);//后置通知
        } catch (Throwable e) {
            e.printStackTrace();
        }finally {
            // 结束后换行
            log.info("=======End=======" + System.lineSeparator());
        }
    }

    private void handlerBefore(ProceedingJoinPoint joinPoint) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获取被增强方法上的注解对象
        SystemLog systemLog = getSystemLog(joinPoint);

        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName   : {}", systemLog.businessName());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",joinPoint.getSignature().getDeclaringTypeName(), ((MethodSignature) joinPoint.getSignature()).getMethod());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));

    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        //获取接口上的实例对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = signature.getMethod().getAnnotation(SystemLog.class);
        return systemLog;
    }

    private void handlerAfter(Object ret) {
        // 打印出参
        log.info("Response       : {}",JSON.toJSONString(ret));
    }

}
